package com.uetoken.cn.activity;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.BankAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.BanksInfo;
import com.uetoken.cn.bean.area.CityBean;
import com.uetoken.cn.bean.area.ProvinceBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.AreaUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class AddBankCardActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView    mIvBack;
    @BindView(R.id.tv_title)
    TextView     mTvTitle;
    @BindView(R.id.edt_activity_add_bank_people)
    EditText     mEdtPeople;
    @BindView(R.id.edt_activity_add_bank_card_no)
    EditText     mEdtCardNo;
    @BindView(R.id.tv_activity_add_bank_next)
    TextView     mTvNext;
    @BindView(R.id.edt_activity_add_bank_name)
    EditText     mEdtBankName;
    @BindView(R.id.edt_activity_add_bank_card_branch_name)
    EditText     mEdtBranchName;
    @BindView(R.id.edt_activity_add_bank_phone)
    EditText     mEdtBankPhone;
    @BindView(R.id.edt_activity_add_bank_card_area)
    EditText     mEdtBankArea;
    /**
     * 获取省市区列表
     */
    private static final int NETWORK_REQUEST_AREA  = 5;
    /**
     * 获取银行卡信息
     */
    private static final int NETWORK_REQUEST_BANKS       = 10;
    /**
     * 新增银行卡的请求码
     */
    private static final int NETWORK_REQUEST_CREATE_BANK = 20;
    /**
     * 所选银行的id
     */
    private  int               bankId;
    private  Dialog            dialog;
    private OptionsPickerView mPickerView;

    /**
     * 用户所选区的id
     */
    private int seLectAreaId;

    /**
     * 省
     */
    private ArrayList<String>                       provinceItems = new ArrayList<>();
    /**
     * 市
     */
    private ArrayList<ArrayList<String>>            cityItems     = new ArrayList<>();


    private List<ProvinceBean> mProvinceBeanList = new ArrayList<>();
    /**
     * 存储在本地的地址
     */
    private String areas;

    private ThreadUtils.SimpleTask<Void> task;

    @Override
    public int getLayoutId() {
        return R.layout.activity_new_bank;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        /*状态栏沉浸式*/
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mTvTitle.setText(getResources().getString(R.string.tv_bank_card));
        mIvBack.setVisibility(View.VISIBLE);

        mPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //选中的第一级的areadid
                int firstAreadid = mProvinceBeanList.get(options1).getAreaid();
                //选中的第二级的areadid
                int secondAreaid = mProvinceBeanList.get(options1).getCityBeans().get(options2).getAreaid();

                if (firstAreadid==secondAreaid){
                    //说明实际只有一级数据
                    seLectAreaId = firstAreadid;
                    mEdtBankArea.setText(provinceItems.get(options1));
                }else{
                    //说明有两级数据,取第二级的areaid和名字
                    seLectAreaId = secondAreaid;
                    mEdtBankArea.setText(cityItems.get(options1).get(options2));
                }
            }
        }).build();
    }

    @Override
    public void initData() {
        areas = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_AREAS_INFO).getString(Constant.SP_AREA, "");
        if (TextUtils.isEmpty(areas)) {
            //本地没有地区数据则请求网络
            showLoading();
            OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getAreaUrl(), NETWORK_REQUEST_AREA, Params.getAreaParams());
        }else{
            //本地有地区数据直接解析数据
            showLoading();
            parseData(areas);
            ThreadUtils.executeByIo(task);
        }
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getBanksUrl(), NETWORK_REQUEST_BANKS, Params.getBanksInfoParams());
    }

    @Override
    public void init() {

    }


    @OnClick({R.id.iv_back, R.id.tv_activity_add_bank_next, R.id.edt_activity_add_bank_name,R.id.edt_activity_add_bank_card_area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.edt_activity_add_bank_name:
                if (dialog!=null){
                    dialog.show();
                }
                break;
            case R.id.tv_activity_add_bank_next:
                createBank();
                break;
            case R.id.edt_activity_add_bank_card_area:
                KeyboardUtils.hideSoftInput(this);
                //选择开户城市
                if (mProvinceBeanList.size()!=0){
                    mPickerView.show();
                }else{
                    ToastUtils.showShort(getResources().getString(R.string.str_area_data_not_loading_finish));
                }
                break;
        }
    }

    /**
     * 遍历数据
     * @param response 存储在本地或者服务器返回的数据
     */
    private void parseData(final String response){
        //开启一个线程池去遍历数据
        task = new ThreadUtils.SimpleTask<Void>() {
            @Nullable
            @Override
            public Void doInBackground() throws Throwable {
                mProvinceBeanList = AreaUtils.parseTwoLevelsData(response);
                initPickerViewData();
                return null;
            }

            @Override
            public void onSuccess(@Nullable Void result) {
                dissmissDialog();
                //只设置两级
                mPickerView.setPicker(provinceItems,cityItems);
            }
        };
    }

    /**
     * 初始化地址选择控件所需要的数据
     */
    private void initPickerViewData() {

        for (ProvinceBean provinceBean : mProvinceBeanList) {
            //该省的城市列表（第二级）
            ArrayList<String> cityList = new ArrayList<>();

            for (CityBean cityBean : provinceBean.getCityBeans()) {

                cityList.add(cityBean.getAreaname());

            }
            provinceItems.add(provinceBean.getAreaname());
            cityItems.add(cityList);
        }
    }




    /**
     * 完成添加银行卡
     */
    private void createBank() {
        String name = mEdtPeople.getText().toString().trim();
        String cardNo = mEdtCardNo.getText().toString().trim();
        String bankName = mEdtBankName.getText().toString().trim();
        String branchBankName = mEdtBranchName.getText().toString().trim();
        String phone = mEdtBankPhone.getText().toString().trim();
        String area = mEdtBankArea.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort(getResources().getString(R.string.str_card_people_not_empty));
            return;
        }
        if (TextUtils.isEmpty(cardNo)) {
            ToastUtils.showShort(getResources().getString(R.string.str_card_no_not_empty));
            return;
        }
        if (TextUtils.isEmpty(bankName)){
            ToastUtils.showShort(getResources().getString(R.string.str_bank_name_not_empty));
            return;
        }
        if (TextUtils.isEmpty(branchBankName)){
            ToastUtils.showShort(getResources().getString(R.string.str_branch_bank_name_not_empty));
            return;
        }
        if (TextUtils.isEmpty(phone)){
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)){
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }

        if (TextUtils.isEmpty(area)){
            ToastUtils.showShort(getResources().getString(R.string.str_bank_account_opening_city_not_empty));
            return;
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(AddBankCardActivity.this,ApiHelper.getUserCreateBankCardUrl(),NETWORK_REQUEST_CREATE_BANK,
                Params.getUserCreateBankCardParams(name,cardNo,String.valueOf(bankId),String.valueOf(seLectAreaId),branchBankName,phone));
    }


    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        try {
            JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
            String message = obj.get("message").getAsString();
            int result = obj.get("result").getAsInt();

            switch (requestCode) {
                case NETWORK_REQUEST_AREA:
                    dissmissDialog();
                    if (result > 0) {
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_AREAS_INFO).put(Constant.SP_AREA, response);
                        parseData(response);
                        ThreadUtils.executeByIo(task);
                    }else{
                        dissmissDialog();
                    }
                    break;
                case NETWORK_REQUEST_BANKS:
                    BanksInfo banksInfo = new Gson().fromJson(response, BanksInfo.class);
                    if (banksInfo.getResult() > 0) {
                        initBankDialog(banksInfo.getData());
                    } else {
                        ToastUtils.showShort(banksInfo.getMessage());
                    }
                    break;
                case NETWORK_REQUEST_CREATE_BANK:
                    dissmissDialog();
                    if (result>0){
                        ToastUtils.showShort(message);
                        setResult(RESULT_OK);
                        finish();
                    }else{
                        ToastUtils.showShort(message);
                    }
                    break;
            }
        } catch (JsonParseException e) {
            ToastUtils.showShort(getResources().getString(R.string.str_json_parse_exception));
        }
    }

    /**
     * 初始化银行信息列表
     *
     * @param data
     */
    private void initBankDialog(final List<BanksInfo.DataBean> data) {
        View view = View.inflate(this, R.layout.dialog_item_banks, null);
        dialog = new Dialog(this, R.style.loading_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display d = windowManager.getDefaultDisplay();
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width = (int) (d.getWidth() * 0.8);
        p.height = (int) (d.getHeight()*0.8);
        dialog.getWindow().setAttributes(p);

        ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.mRyDialogItemBanks.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        BankAdapter bankAdapter = new BankAdapter(R.layout.item_bank,data);
        viewHolder.mRyDialogItemBanks.setAdapter(bankAdapter);

        bankAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                dialog.dismiss();
                //当前选择的银行
                BanksInfo.DataBean dataBean = data.get(position);
                mEdtBankName.setText(dataBean.getBankchinaname());
                bankId = dataBean.getBankinfoid();
            }
        });
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    static class ViewHolder {
        @BindView(R.id.ry_dialog_item_banks)
        RecyclerView mRyDialogItemBanks;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onDestroy() {
        if (task!=null){
            task.cancel();
        }
        super.onDestroy();
    }
}
